package cn.edu.zust.se.mvcdb.service.impl;

import cn.edu.zust.se.mvcdb.service.UserService;
import cn.edu.zust.se.mvcdb.util.DBUtil;
import cn.edu.zust.se.mvcdb.vo.User;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class UserServiceImpl implements UserService {
    @Override
    public List<User> getAllUsers() {
//        DBUtil.openConnection("jdbc:mysql://localhost:3306/test_db?characterEncoding=utf-8","root","123456");
        ResultSet rs=DBUtil.select("select * from user");
        List<User> list=new ArrayList<>();
        try {
            while (rs.next()) {
                User u = rs2User(rs);
                list.add(u);
            }
        }catch (SQLException sqlException) {
        }finally {
//            DBUtil.closeConnection();
            return list;
        }
    }

    @Override
    public User login(String userName, String password) {
//        DBUtil.openConnection("jdbc:mysql://localhost:3306/test_db?characterEncoding=utf-8","root","123456");
        ResultSet rs=DBUtil.select("select * from user where username='"+userName+"' and password='"+password+"'");
        User u=null;
        try {
            if (rs.next()) {
                u = rs2User(rs);
                if (rs.next()) {
                    u=null;
                }
            }
        }catch (SQLException sqlException) {
        }finally {
//            DBUtil.closeConnection();
            return u;
        }
    }

    private User rs2User(ResultSet rs) throws SQLException {
        User u=new User();
        u.setId(rs.getInt("id"));
        u.setName(rs.getString("name"));
        u.setPassword(rs.getString("password"));
        u.setUserName(rs.getString("username"));
        return u;
    }
}
